package service_blog_mirchen_com

import (
	"gen-go/BlogServices"
	"github.com/jinzhu/gorm"
	"fmt"
)

//service结构
type ArticleServiceHandler struct {
	orm *gorm.DB
}

//文章模型结构
type Article struct {
	Id          int64  `gorm:"primary_key"`
	Title       string
	Keywords    string
	Description string
	Imgurl      string
	Content     string
	CatId       int64
	Sort        int64
	CreateAt    int64
	UpdateAt    int64
	Viewnum     int64
	Url         string
}

func NewArticleServiceHandler(getOrm *gorm.DB) *ArticleServiceHandler {
	return &ArticleServiceHandler{orm:getOrm}
}

func (ats *ArticleServiceHandler) GetArticles(where string, offset, limit int64) ([]*BlogServices.Article, error) {
	articles := &[]Article{}
	result := []*BlogServices.Article{}
	err := ats.orm.Where(where).Limit(limit).Offset(offset).Find(articles).Error;
	if err == nil {
		if len(*articles) > 0 {
			for _, article := range *articles {
				result = append(result, &BlogServices.Article{
					ID:          article.Id,
					Title:       article.Title,
					Keywords:    article.Keywords,
					Description: article.Description,
					Imgurl:      article.Imgurl,
					Content:     article.Content,
					CatId:       article.CatId,
					Sort:        article.Sort,
					CreateAt:    article.CreateAt,
					UpdateAt:    article.UpdateAt,
					ViewNum:     article.Viewnum,
					URL:         article.Url,
				})
			}
		}
		return result, nil;
	}
	return result, err
}

func (ats *ArticleServiceHandler) GetArticlesByCatId(catid, offset, limit int64) ([]*BlogServices.Article, error) {
	return []*BlogServices.Article{}, nil
}

func (ats *ArticleServiceHandler) GetArticleById(id int64) (*BlogServices.Article, error) {
	article := Article{}
	err := ats.orm.Where("id=?", id).Order("id Desc").First(&article).Error
	if err != nil {
		return &BlogServices.Article{}, nil
	} else {
		return &BlogServices.Article{
			ID:          article.Id,
			Title:       article.Title,
			Keywords:    article.Keywords,
			Description: article.Description,
			Imgurl:      article.Imgurl,
			Content:     article.Content,
			CatId:       article.CatId,
			Sort:        article.Sort,
			CreateAt:    article.CreateAt,
			UpdateAt:    article.UpdateAt,
			ViewNum:     article.Viewnum,
			URL:         article.Url,
		}, nil
	}

}

func (ats *ArticleServiceHandler) GetArticleTotal(where string) (int64, error) {
	var total int64
	err := ats.orm.Where(where).Table("learn_article").Count(&total).Error;
	fmt.Println("total",total)
	return total,err
}